use crate::config::server::ConfigEntry;
use crate::discovery::ServiceInstance;
use crate::discovery::server::Service;
use crate::namespace::server::Namespace;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::io::Cursor;

pub mod api;
mod declare_types;
pub mod network;
pub mod store;

pub use api::raft_write as write;

// 1. 定义客户端的请求和响应
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(tag = "cmd", content = "data")]
pub enum RaftRequest {
    /// 设置键值对
    Set { key: String, value: String },
    /// 删除键值对
    Delete { key: String },
    /// 配置中心设置配置
    SetConfig { entry: ConfigEntry },
    /// 配置中心更新配置
    UpdateConfig { entry: ConfigEntry },
    /// 配置中心删除配置
    DeleteConfig { namespace_id: String, id: String },
    /// 新增或更新命名空间
    UpsertNamespace { namespace: Namespace },
    /// 删除命名空间
    DeleteNamespace { id: String },
    /// 注册服务
    RegisterService { service: Service },
    /// 注销服务
    DeregisterService {
        namespace_id: String,
        service_id: String,
    },
    /// 注册服务实例
    RegisterServiceInstance {
        namespace_id: String,
        instance: ServiceInstance,
    },
    /// 注销服务实例
    DeregisterServiceInstance {
        namespace_id: String,
        service_id: String,
        instance_id: String,
    },
    /// 服务实例心跳
    Heartbeat {
        namespace_id: String,
        service_id: String,
        instance_id: String,
    },
    /// 缓存写入
    CacheWrite {
        key: String,
        value: Value,
        ttl: Option<u64>,
    },
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RaftResponse {
    pub value: Option<String>,
}

// 2. 定义Raft需要的类型配置
openraft::declare_raft_types!(
    pub TypeConfig:
        D = RaftRequest,
        R = RaftResponse,
);
pub type Raft = openraft::Raft<TypeConfig>;

// 3. 实现日志存储和状态机
pub type LogStore = store::SledLogStore<TypeConfig>;
pub type StateMachine = store::StateMachineStore;

// 4. 实现网络层
pub type Network = network::NetworkFactory;

// 节点ID
pub type NodeId = u64;
